#include "DataBase.h"
#include <iostream>


DataBase::DataBase(void)
{
}

DataBase::~DataBase(void)
{
}

void DataBase::initDatabase()
{
	m_alive = true;
	LoaderConfig	loader("D:\\Libraries\\Documents\\Visual Studio 2010\\Projects\\TheHunter\\TheHunter\\config.ini");

	m_fps = atoi(loader.getValue("FPS").c_str());
	m_port = atoi(loader.getValue("PORT").c_str());

	m_maxPlayers = atoi(loader.getValue("NB_PLAYERS").c_str());

	LogController::getInstance()->AddToLog(LogController::L_NOTICE, "Load config done");

	setState(GameState::WAIT_CLIENTS);
	m_typeGenerate = true;
}


void DataBase::pushBackClient(Client *client)
{
	m_mutexClients.lock();
	m_clients.push_back(client);
	m_mutexClients.unlock();
}

void DataBase::eraseClientAt(int pos)
{
	m_mutexClients.lock();
	if (pos < m_clients.size())
	m_clients.erase(m_clients.begin() + pos);		
	m_mutexClients.unlock();
}

int DataBase::getSizeClients()
{
	m_mutexClients.lock();
	int size = m_clients.size();
	m_mutexClients.unlock();
	return size;
}

Client*	DataBase::getElementAt(int pos)
{
	m_mutexClients.lock();
	Client *t = NULL;
	if (pos < m_clients.size())
		t = m_clients[pos];
	m_mutexClients.unlock();
	return t;
}

void	DataBase::pushStackRecv(SPacket *sp)
{
	m_mutexStackRecv.lock();
	m_stackRecv.push_back(sp);
	m_mutexStackRecv.unlock();
}

SPacket*	DataBase::popStackRecv()
{
	m_mutexStackRecv.lock();
	SPacket *sp = NULL;
	if (m_stackRecv.size() > 0) 
	{
		sp = m_stackRecv[0];
		m_stackRecv.erase(m_stackRecv.begin());
	}
	else
		sp = NULL;
	m_mutexStackRecv.unlock();
	return sp;
}

GameState	DataBase::getCurrentState()
{
	m_mutexState.lock();
	GameState t = m_state;
	m_mutexState.unlock();
	return t;
}

void	DataBase::setState(GameState ngs)
{
	m_mutexState.lock();
	m_state = ngs;
	m_mutexState.unlock();
}

void	DataBase::pushStackSend(SPacket *sp)
{
	m_mutexStackSend.lock();
	m_stackSend.push_back(sp);
	m_mutexStackSend.unlock();
}

SPacket* DataBase::popStackSend()
{
	m_mutexStackSend.lock();
	SPacket *sp = NULL;
	if (m_stackSend.size() > 0)
	{
		sp = m_stackSend[0];
		m_stackSend.erase(m_stackSend.begin());
	}
	m_mutexStackSend.unlock();
	return sp;
}

int DataBase::getSizeStackSend()
{
	m_mutexStackSend.lock();
	int s = m_stackSend.size();
	m_mutexStackSend.unlock();
	return s;
}

int DataBase::getSizeStackRecv()
{
	m_mutexStackRecv.lock();
	int s = m_stackRecv.size();
	m_mutexStackRecv.unlock();
	return s;
}